<?php
/**
 * @title 剑指 Offer 11. 旋转数组的最小数字 - 二分
 * @author start2004
 */

class Solution {

    /**
     * @param Integer[] $numbers
     * @return Integer
     */
    function minArray($numbers) {
        /**
         * @since 2020-07-22 左右指针
         */
        $left = 0;
        $right = count($numbers)-1;

        /**
         * @since 2020-07-22 极端情况
         */
        if($right == 0){
            return $numbers[0];
        } else {}

        /**
         * @since 2020-09-16 二分查找
         */
        while($left<$right){
            $mid = ($left+$right)>>1;

            /**
             * @since 2020-09-16 [mid, right]升序, 区间里mid是最小值, 抹去[mid+1, right]
             */
            if($numbers[$mid] < $numbers[$right]){
                $right = $mid;
            } elseif($numbers[$mid] > $numbers[$right]) {
                /**
                 * @since 2020-09-16 必有1段升序, 最小值在非升序列, [mid+1, right]
                 */
                $left = $mid+1;
            } else {
                /**
                 * @since 2020-09-16 mid == right, right可以抹去
                 */
                $right--;
            }
        }

        /**
         * @return
         */
        return $numbers[$left];
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.22_2.php
 */
$datas = [
    [3,3,3,1,3],
    [3,1,3,3,3],
    [1,3,5],
    [3,4,5,1,2],
    [2,2,2,0,1],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->minArray($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
